# Copyright (c) 2024, kaepyz@gmail.com and contributors
# For license information, please see license.txt

from typing import List, Dict, Tuple, Optional
from datetime import datetime, timedelta
import frappe
from .client import TongToolClient, get_tongtool_client


class OrderAPI:
    """通途订单API"""
    
    def __init__(self, client: TongToolClient = None):
        self.client = client or get_tongtool_client()
    
    def get_orders(self, params: Dict) -> Tuple[List[Dict], bool]:
        """
        获取订单列表
        
        Args:
            params: {
                'sale_date_from': '2024-01-01 00:00:00',
                'sale_date_to': '2024-01-01 23:59:59',
                'page_no': 1,
                'page_size': 100,
                'order_status': 'despatched',  # 可选
                'platform_code': 'amazon',     # 可选
                'account_code': 'FZHSX'        # 可选
            }
        
        Returns:
            Tuple[List[Dict], bool]: (订单列表, 是否最后一页)
        """
        # 检查缓存
        cache_key = self.client.get_cache_key(f"orders_{params}")
        cached_data = self.client.get_cached_data(cache_key)
        if cached_data:
            return cached_data['orders'], cached_data['is_last_page']
        
        # 设置默认参数
        request_params = {
            'pageNo': params.get('page_no', 1),
            'pageSize': min(params.get('page_size', 100), 100),  # 通途限制最大100
            'storeFlag': '0'  # 0：活跃表、1：一年表、2：归档表
        }
        
        # 必填参数
        if 'sale_date_from' in params:
            request_params['saleDateFrom'] = params['sale_date_from']
        if 'sale_date_to' in params:
            request_params['saleDateTo'] = params['sale_date_to']
        
        # 可选参数
        if params.get('order_status'):
            request_params['orderStatus'] = params['order_status']
        if params.get('platform_code'):
            request_params['platformCode'] = params['platform_code']
        if params.get('account_code'):
            request_params['accountCode'] = params['account_code']
        if params.get('order_id'):
            request_params['orderId'] = params['order_id']
        if params.get('buyer_email'):
            request_params['buyerEmail'] = params['buyer_email']
        
        try:
            response = self.client.request('POST', '/openapi/tongtool/ordersQuery', request_params)
            
            datas = response.get('datas', {})
            orders = datas.get('array', [])
            is_last_page = len(orders) < request_params['pageSize']
            
            # 数据后处理
            processed_orders = []
            for order in orders:
                processed_order = self._process_order_data(order)
                processed_orders.append(processed_order)
            
            # 缓存结果
            cache_data = {
                'orders': processed_orders,
                'is_last_page': is_last_page
            }
            self.client.set_cached_data(cache_key, cache_data)
            
            return processed_orders, is_last_page
            
        except Exception as e:
            frappe.log_error(f"获取通途订单失败: {str(e)}")
            raise
    
    def get_order(self, order_id: str) -> Optional[Dict]:
        """
        获取单个订单
        
        Args:
            order_id: 通途订单号
            
        Returns:
            Dict: 订单数据，如果不存在返回None
        """
        try:
            orders, _ = self.get_orders({
                'order_id': order_id,
                'page_no': 1,
                'page_size': 1
            })
            
            for order in orders:
                if order.get('orderIdCode') == order_id:
                    return order
            
            return None
            
        except Exception as e:
            frappe.log_error(f"获取通途订单失败 {order_id}: {str(e)}")
            return None
    
    def get_fba_orders(self, params: Dict) -> List[Dict]:
        """
        获取FBA订单
        
        Args:
            params: {
                'purchase_date_from': '2024-01-01 00:00:00',
                'purchase_date_to': '2024-01-01 23:59:59',
                'account': 'AMZFZHSXUS',  # 可选
                'page_no': 1,
                'page_size': 100
            }
        
        Returns:
            List[Dict]: FBA订单列表
        """
        # 检查缓存
        cache_key = self.client.get_cache_key(f"fba_orders_{params}")
        cached_data = self.client.get_cached_data(cache_key)
        if cached_data:
            return cached_data
        
        request_params = {
            'pageNo': params.get('page_no', 1),
            'pageSize': min(params.get('page_size', 100), 100),
            'purchaseDateFrom': params.get('purchase_date_from'),
            'purchaseDateTo': params.get('purchase_date_to')
        }
        
        if params.get('account'):
            request_params['account'] = params['account']
        
        try:
            response = self.client.request('POST', '/openapi/tongtool/fbaOrderQuery', request_params)
            
            datas = response.get('datas', {})
            fba_orders = datas.get('array', [])
            
            # 数据后处理
            processed_orders = []
            for order in fba_orders:
                processed_order = self._process_fba_order_data(order)
                processed_orders.append(processed_order)
            
            # 缓存结果
            self.client.set_cached_data(cache_key, processed_orders)
            
            return processed_orders
            
        except Exception as e:
            frappe.log_error(f"获取通途FBA订单失败: {str(e)}")
            raise
    
    def _process_order_data(self, order: Dict) -> Dict:
        """处理单个订单数据"""
        processed = order.copy()
        
        # 处理布尔值字段
        processed['is_invalid'] = order.get('isInvalid') not in ['0', '', None]
        processed['is_suspended'] = order.get('isSuspended') == '1'
        
        # 处理订单明细
        order_details = order.get('orderDetails', [])
        processed_details = []
        
        for detail in order_details:
            processed_detail = detail.copy()
            
            # 判断是否需要发货
            is_deliver_goods = detail.get('isDeliverGoods')
            if is_deliver_goods == '0':
                processed_detail['required_delivery'] = True
            elif is_deliver_goods == '1':
                processed_detail['required_delivery'] = False
            else:
                processed_detail['required_delivery'] = None
            
            processed_details.append(processed_detail)
        
        processed['orderDetails'] = processed_details
        
        # 添加订单类型判断
        processed['order_type'] = self._determine_order_type(order)
        
        return processed
    
    def _process_fba_order_data(self, order: Dict) -> Dict:
        """处理FBA订单数据"""
        processed = order.copy()
        processed['order_type'] = 'FBA'
        
        # 转换时间戳
        if order.get('purchaseDate'):
            try:
                processed['purchase_date_formatted'] = datetime.fromtimestamp(
                    order['purchaseDate'] / 1000
                ).strftime('%Y-%m-%d %H:%M:%S')
            except:
                processed['purchase_date_formatted'] = None
        
        return processed
    
    def _determine_order_type(self, order: Dict) -> str:
        """判断订单类型"""
        warehouse_name = order.get('warehouseName', '').lower()
        
        # 根据仓库名称判断
        if 'fba' in warehouse_name or 'amazon' in warehouse_name:
            return 'FBA'
        elif any(keyword in warehouse_name for keyword in ['自发货', 'self', 'own']):
            return '自发货'
        else:
            # 根据包裹信息判断
            package_info = order.get('packageInfoList', [])
            if package_info:
                return '自发货'
            else:
                return '未知'
    
    def get_orders_by_date_range(self, start_date: str, end_date: str, 
                                order_type: str = 'all') -> List[Dict]:
        """
        按日期范围获取所有订单（自动分页）
        
        Args:
            start_date: 开始日期 '2024-01-01'
            end_date: 结束日期 '2024-01-01' 
            order_type: 订单类型 'all', 'self_fulfillment', 'fba'
            
        Returns:
            List[Dict]: 所有订单列表
        """
        all_orders = []
        
        try:
            # 自发货订单
            if order_type in ['all', 'self_fulfillment']:
                page_no = 1
                while True:
                    orders, is_last_page = self.get_orders({
                        'sale_date_from': f'{start_date} 00:00:00',
                        'sale_date_to': f'{end_date} 23:59:59',
                        'page_no': page_no,
                        'page_size': 100
                    })
                    
                    all_orders.extend(orders)
                    
                    if is_last_page:
                        break
                    
                    page_no += 1
            
            # FBA订单
            if order_type in ['all', 'fba']:
                fba_orders = self.get_fba_orders({
                    'purchase_date_from': f'{start_date} 00:00:00',
                    'purchase_date_to': f'{end_date} 23:59:59',
                    'page_no': 1,
                    'page_size': 100
                })
                
                all_orders.extend(fba_orders)
            
            frappe.logger().info(f"获取{start_date}到{end_date}的订单共{len(all_orders)}条")
            return all_orders
            
        except Exception as e:
            frappe.log_error(f"按日期范围获取订单失败: {str(e)}")
            raise
